package hystrix.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import hystrix.service.HystrixProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController

public class HystrixProviderController {
    @Autowired
    private HystrixProviderService hystrixProviderService;

    /**
     * 熔断的回调方法
     */
    public String hystrixFunction(){
        return "hystrix_provider_error";
    }

    /**
     * 服务熔断 -- 程序异常
     */
    @GetMapping("/c1")
    @HystrixCommand(fallbackMethod = "hystrixFunction", commandProperties = {
            /**
             * 服务降级 =》 进而熔断 =》 恢复调用链路（正确率恢复）
             * 10s内，10次请求中失败率达到60%则熔断（10次请求中6次失败）
             */
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
    })
    public String c1(){
        String msg = hystrixProviderService.s1();
        if(msg == null){
            throw new RuntimeException("信息错误");
        }
        return msg;
    }

    /**
     * 服务熔断 -- 超时
     */
    @GetMapping("/c2")
    @HystrixCommand(fallbackMethod = "hystrixFunction", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value="3000"),  //超过3s  服务熔断
    })
    public String c2(){
        try{
            TimeUnit.SECONDS.sleep(3);
            return "hystrix_provider_9101_c2";
        }catch (InterruptedException e){
            e.printStackTrace();
            return "hystrix_provider_9101_c2_error";
        }
    }

    /**
     * 没有熔断 -- 异常
     */
    @GetMapping("/c3")
    public String c3(){
        if(System.currentTimeMillis()%2 == 0) {
            return "hystrix_provider_9101_c3";
        }else{
            throw new RuntimeException("信息错误");
        }
    }

    /**
     * 没有熔断 -- 超时
     */
    @GetMapping("/c4")
    public String c4(){
        try{
            TimeUnit.SECONDS.sleep(5);
            return "hystrix_provider_9101_c4";
        }catch (InterruptedException e){
            e.printStackTrace();
            return "hystrix_provider_9101_c4_error";
        }
    }
}
